<?php

namespace App\Task\Spread;

use App\Model\Spread\SpreadAccount;
use App\Model\Spread\SpreadLog;
use App\Model\Spread\StatCpa;
use Hyperf\Crontab\Annotation\Crontab;

/**
 * 每日统计5,15,35,50 *\/1 * * *   ｜｜｜｜｜｜
 * @Crontab(name="SpreadStatTask", rule="5,15,35,50 *\/1 * * *", callback="execute", memo="每日cpa数据统计", singleton=false)
 */
class SpreadStatTask
{
    /**
     * @return void
     */
    public function execute()
    {
        log_info(__CLASS__ . "==Start==cpa统计" . date('Y-m-d H:i:s'));

        $day = date('Y-m-d');

        if (time() - strtotime(date('Y-m-d')) < 300) {
            $day = date('Y-m-d',strtotime('-1 days'));
        }

        $startDate = $day.' 00:00:00';
        $endDate = $day.' 23:59:59';

        $channels = SpreadAccount::where('status',1)->where('channel_type',1)->get()->toArray();

        foreach ($channels as  $channel){
            $model = StatCpa::query()->where([
                ['dt','=',$day],
                ['s_id','=',$channel['id']],
                ['p_id','=',$channel['parent_id']]
            ])->first();

            $rechargeRmb = $model->recharge;
            if(empty($model)){
                $model = new StatCpa();
                $rechargeRmb = 0;
            }

            $total = (new SpreadLog())->getTotalCountBySid($channel['id'],$startDate,$endDate);
            if ($total == 0) {
                continue;
            }

            $k = 0;
            if ($channel['discount_proportion'] > 0) {
                $k = bcmul((string)$total,bcdiv((string)$channel['discount_proportion'],"100",1),0);
            }

            $model->s_id = $channel['id'];
            $model->p_id = $channel['parent_id'];
            $model->dt = $day;
            $model->reg = $total;
            $model->reg_k = $total - $k;
            $model->recharge = $rechargeRmb;
            $model->is_settle = 0;
            $model->save();
        }
    }
}